package com.kun.portal.webframe.service;

import com.kun.portal.webframe.dao.*;
import com.kun.portal.webframe.po.*;
import com.kun.portal.webframe.util.MessageEmit;
import com.kun.portal.webframe.util.PageImpl;
import com.kun.portal.webframe.util.eventQuene.Message;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;

import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.persistence.EntityManager;
import javax.persistence.Query;
import javax.persistence.TemporalType;
import javax.persistence.criteria.*;
import java.lang.reflect.Array;
import java.util.*;

/**
 * Created by Administrator on 2018/5/23.
 */
@Service
public class GroundServiceSchedulingService  {
    @Autowired
    private GroundServiceSchedulingDao groundServiceSchedulingDao;
    @Autowired
    private EntityManager entityManager;
    @Autowired
    private GroundServiceSchedulingsDao groundServiceSchedulingsDao;
    @Autowired

    private  FwUserDao fwUserDao ;
    @Autowired
    private FwTeamDao fwTeamDao;

    @Autowired
    private CourseNodeDao courseNodeDao;
    public Page<GroundServiceFlightPlaneView> query( Pageable pageable,Date  startDate,Date endDate,String flightInfoId,Boolean scheduled){
        String quString="";
        if(scheduled!=null){
            if(scheduled){
                quString = "select new com.kun.portal.webframe.po.GroundServiceFlightPlaneView(f,g) from GroundServiceSchedulings g Left JOIN  FlightPlanePo f  on g.planeId = f.planeId where 1=1 ";
            }else{
                quString = "select new com.kun.portal.webframe.po.GroundServiceFlightPlaneView(f,g) from GroundServiceSchedulings g  RIGHT JOIN  FlightPlanePo f  on g.planeId = f.planeId where g.planeId ";
            }
        }else{
            quString = "select new com.kun.portal.webframe.po.GroundServiceFlightPlaneView(f,g) from GroundServiceSchedulings g  RIGHT JOIN  FlightPlanePo f  on g.planeId = f.planeId where 1=1 ";
        }

        Map<String,Object> params =  new HashMap<>();
        if(StringUtils.isNoneBlank(flightInfoId)){
            quString += "  and f.flightInfo.flightInfoId= :flightInfoId";
            params.put("flightInfoId",flightInfoId);
        }
        if(startDate !=null){
            quString += "  and f.expectDate >= :startDate";
            params.put("startDate",startDate);
        }
        if(endDate !=null){
            quString += "  and f.expectDate <= :endDate";
            params.put("endDate",endDate);
        }
         Query quey= entityManager.createQuery(quString);
        for( String s : params.keySet()){
            if(params.get(s) instanceof  Date){
                quey.setParameter(s,(Date)params.get(s), TemporalType.DATE);
            }else{
                quey.setParameter(s,params.get(s));
            }

        }

        return  new PageImpl<GroundServiceFlightPlaneView>(quey,pageable);
        //   return quey.getResultList();
//        String s="402880f3636803c5016368060fde0000";
//        return groundServiceSchedulingDao.findFlightInfoId (s,pageable);
    }



    public Page<GroundServiceSchedulings> queryByCon(Pageable pageable){
        Specification<GroundServiceSchedulings> query = new Specification<GroundServiceSchedulings>() {
            @Override
            public Predicate toPredicate(Root<GroundServiceSchedulings> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
                Predicate equal= cb.equal(root.join("flightPlanePo", JoinType.LEFT).get("flightInfo").get("flightInfoId"),"402880f3636c170601636c26026e0001");
                return equal;
            }
        };
       return  groundServiceSchedulingsDao.findAll(query,pageable);
    }

    @Transactional
    public GroundServiceSchedulings scheduleAuto(FlightPlanePo flightPlanePo){
        //未完成 select f,s from  GroundServiceSchedulings g  join g.schedulings  s ,FlightPlanePo  f where g.planeId = f.planeId  and s.status != "结束"
        //待排班
        List<GroundServiceSchedulings>  unfinishedSchedule =entityManager.createQuery("select distinct g from  GroundServiceSchedulings g left join fetch  g.flightPlanePo f left join fetch f.flightInfo left join fetch g.schedulings  s left join fetch s.selectedFwUser left join fetch s.airSecurityVehiclePo  left join fetch s.groundServiceItemPo  where  not(s.status= '结束')").getResultList();


        Map<String , FlightPlaneSchedule> filterUserMap  = new HashMap<>();
        Map<String ,FlightPlaneSchedule> filterTeamMap = new HashMap<>();
        for( GroundServiceSchedulings gs :unfinishedSchedule){

                for(GroundServiceScheduling scheduling: gs.getSchedulings()){
                    for(FwUserPo user :scheduling.getSelectedFwUser()){
                        filterUserMap.put(user.getUserId(),new FlightPlaneSchedule(scheduling.getGroundServiceItemPo(),gs.getFlightPlanePo()));
                        filterTeamMap.put(scheduling.getSelectedTeamId(),new FlightPlaneSchedule(scheduling.getGroundServiceItemPo(),gs.getFlightPlanePo()));
                    }
            }
        }
        List<GroundServiceItemPo> groundServiceItemPos = entityManager.createQuery("select distinct g from  GroundServiceItemPo g left join fetch g.airSecurityVehicle left join  fetch  g.teams  t left join fetch t.userList").getResultList();
        GroundServiceSchedulings groundServiceSchedulings = new GroundServiceSchedulings();
        //groundServiceSchedulings.setPlaneId(flightPlanePo.getPlaneId());
        groundServiceSchedulings.setFlightPlanePo (flightPlanePo);
        HashSet<GroundServiceScheduling> gss = new HashSet<GroundServiceScheduling>();

        for(GroundServiceItemPo  g:groundServiceItemPos){
            List<FwTeamPo> teams = new ArrayList<>(g.getTeams()) ;
            for(int i=0;i<teams.size();i++){
                if(teams.get(i).getUserList()==null||teams.get(i).getUserList().size()==0){
                    teams.remove(i);
                }
            }
            if(teams==null||teams.size()==0){
                continue;
            }
            int userSize= 0;
            for(FwTeamPo teamPo : teams){
                userSize+=teamPo.getUserList()==null?0:teamPo.getUserList().size();
            }
            if(userSize==0){
                continue;
            }
            if(flightPlanePo.getImportOrExport()=="进港"){
               if(!g.getUseInImport()){
                   continue;
               }
            }
            if(flightPlanePo.getImportOrExport()=="出港"){
                if(!g.getUseInExport()){
                    continue;
                }
            }
            if(flightPlanePo.getImportOrExport()=="中转联程"){
                if(g.getUseInTransferProcess()){
                    continue;
                }
            }
            GroundServiceScheduling gs =  new GroundServiceScheduling();
            gs.setGroundServiceItemPo(g);
            List<FwUserPo> fwusers = new ArrayList<FwUserPo>();
            if(g.isHasGroup()){
                teams.sort(new Comparator<FwTeamPo>() {
                    @Override
                    public int compare(FwTeamPo o1, FwTeamPo o2) {
                        if(filterTeamMap!=null){
                            FlightPlaneSchedule o1Flight= filterTeamMap.get(o1.getTeamId());
                            FlightPlaneSchedule  o2Flight = filterTeamMap.get(o2.getTeamId());;
                            if((o1Flight==null||o2Flight==null)&&!(o1Flight==null&&o2Flight==null)){
                                return o1Flight==null ?-1:1;
                            }
                            if(o1Flight!=null&&o2Flight!=null){
                                Date baseTime =  null;
                                Date o1Time = null;
                                Date o2Time = null;

                                if(flightPlanePo.getImportOrExport()=="进港"){
                                    if(g.getImportTimeStrategy()=="takeoffTime"){
                                       baseTime = flightPlanePo.getTakeOffTime();
                                    }
                                    if(g.getImportTimeStrategy()=="arriveTime"){
                                        baseTime = flightPlanePo.getArriveTime();
                                    }
                                }
                                if(flightPlanePo.getImportOrExport()=="出港"){
                                    if(g.getExportTimeStrategy()=="takeoffTime"){
                                        baseTime = flightPlanePo.getTakeOffTime();
                                    }
                                    if(g.getExportTimeStrategy()=="arriveTime"){
                                        baseTime = flightPlanePo.getArriveTime();
                                    }
                                }
                                if(flightPlanePo.getImportOrExport()=="中转联程"){
                                    if(g.getTransferProcessStrategy()=="takeoffTime"){
                                        baseTime = flightPlanePo.getTakeOffTime();
                                    }
                                    if(g.getTransferProcessStrategy()=="arriveTime"){
                                        baseTime = flightPlanePo.getArriveTime();
                                    }
                                }

                                if(o1Flight.getFlightPlanePo().getImportOrExport()=="进港"){
                                    if(o1Flight.getGroundServiceItemPo().getImportTimeStrategy()=="takeoffTime"){
                                        o1Time = o1Flight.getFlightPlanePo().getTakeOffTime();
                                    }
                                    if(o1Flight.getGroundServiceItemPo().getImportTimeStrategy()=="arriveTime"){
                                        o1Time = o1Flight.getFlightPlanePo().getArriveTime();
                                    }
                                }
                                if(o1Flight.getFlightPlanePo().getImportOrExport()=="出港"){
                                    if(o1Flight.getGroundServiceItemPo().getExportTimeStrategy()=="takeoffTime"){
                                        o1Time = o1Flight.getFlightPlanePo().getTakeOffTime();
                                    }
                                    if(o1Flight.getGroundServiceItemPo().getExportTimeStrategy()=="arriveTime"){
                                        o1Time = o1Flight.getFlightPlanePo().getArriveTime();
                                    }
                                }
                                if(o1Flight.getFlightPlanePo().getImportOrExport()=="中转联程"){
                                    if(o1Flight.getGroundServiceItemPo().getTransferProcessStrategy()=="takeoffTime"){
                                        o1Time = o1Flight.getFlightPlanePo().getTakeOffTime();
                                    }
                                    if(o1Flight.getGroundServiceItemPo().getTransferProcessStrategy()=="arriveTime"){
                                        o1Time = o1Flight.getFlightPlanePo().getArriveTime();
                                    }
                                }
                                if(o2Flight.getFlightPlanePo().getImportOrExport()=="进港"){
                                    if(o2Flight.getGroundServiceItemPo().getImportTimeStrategy()=="takeoffTime"){
                                        o2Time = o2Flight.getFlightPlanePo().getTakeOffTime();
                                    }
                                    if(o2Flight.getGroundServiceItemPo().getImportTimeStrategy()=="arriveTime"){
                                        o2Time = o2Flight.getFlightPlanePo().getArriveTime();
                                    }
                                }
                                if(o2Flight.getFlightPlanePo().getImportOrExport()=="出港"){
                                    if(o2Flight.getGroundServiceItemPo().getExportTimeStrategy()=="takeoffTime"){
                                        o2Time = o2Flight.getFlightPlanePo().getTakeOffTime();
                                    }
                                    if(o2Flight.getGroundServiceItemPo().getExportTimeStrategy()=="arriveTime"){
                                        o2Time = o2Flight.getFlightPlanePo().getArriveTime();
                                    }
                                }
                                if(o2Flight.getFlightPlanePo().getImportOrExport()=="中转联程"){
                                    if(o2Flight.getGroundServiceItemPo().getTransferProcessStrategy()=="takeoffTime"){
                                        o2Time = o2Flight.getFlightPlanePo().getTakeOffTime();
                                    }
                                    if(o2Flight.getGroundServiceItemPo().getTransferProcessStrategy()=="arriveTime"){
                                        o2Time = o2Flight.getFlightPlanePo().getArriveTime();
                                    }
                                }
                                long o1abs = Math.abs(o1Time.getTime() - baseTime.getTime());
                                long o2abs = Math.abs(o2Time.getTime() - baseTime.getTime());
                                if(o1abs!=o2abs){
                                    return  o1abs>o2abs?-1:1;
                                }


                            }
                        }
                        if(o1.getServiceTime()==o2.getServiceTime()){
                            return 0;
                        }
                        if(o1.getServiceTime()>o2.getServiceTime()){
                            return 1;
                        }else{
                            return -1;
                        }
                    }
                });
                ArrayList<FwUserPo> ue = new ArrayList<FwUserPo>();
                ue.addAll(teams.get(0).getUserList());
                FwTeamPo teamPo = teams.get(0);
                teamPo.setServiceTime(teamPo.getServiceTime()+1);
                fwTeamDao.save(teamPo);
                gs.setSelectedFwUser(ue);
                gs.setSelectedTeamId(teamPo.getTeamId());

            }else{
                List<FwUserPo> fwUserPos =  new ArrayList<FwUserPo>();
                for(FwTeamPo teamPo : teams){
                    if(teamPo.getUserList()!=null&&teamPo.getUserList().size()>0){
                        fwUserPos.addAll(teamPo.getUserList());
                    }
                }
                fwUserPos.sort(new Comparator<FwUserPo>() {
                    @Override
                    public int compare(FwUserPo o1, FwUserPo o2) {
                        if(filterTeamMap!=null){
                            FlightPlaneSchedule o1Flight= filterUserMap.get(o1.getUserId());
                            FlightPlaneSchedule  o2Flight = filterUserMap.get(o2.getUserId());;
                            if((o1Flight==null||o2Flight==null)&&!(o1Flight==null&&o2Flight==null)){
                                return o1Flight==null ?-1:1;
                            }
                            if(o1Flight!=null&&o2Flight!=null){
                                Date baseTime =  null;
                                Date o1Time = null;
                                Date o2Time = null;

                                if(flightPlanePo.getImportOrExport()=="进港"){
                                    if(g.getImportTimeStrategy()=="takeoffTime"){
                                        baseTime = flightPlanePo.getTakeOffTime();
                                    }
                                    if(g.getImportTimeStrategy()=="arriveTime"){
                                        baseTime = flightPlanePo.getArriveTime();
                                    }
                                }
                                if(flightPlanePo.getImportOrExport()=="出港"){
                                    if(g.getExportTimeStrategy()=="takeoffTime"){
                                        baseTime = flightPlanePo.getTakeOffTime();
                                    }
                                    if(g.getExportTimeStrategy()=="arriveTime"){
                                        baseTime = flightPlanePo.getArriveTime();
                                    }
                                }
                                if(flightPlanePo.getImportOrExport()=="中转联程"){
                                    if(g.getTransferProcessStrategy()=="takeoffTime"){
                                        baseTime = flightPlanePo.getTakeOffTime();
                                    }
                                    if(g.getTransferProcessStrategy()=="arriveTime"){
                                        baseTime = flightPlanePo.getArriveTime();
                                    }
                                }

                                if(o1Flight.getFlightPlanePo().getImportOrExport()=="进港"){
                                    if(o1Flight.getGroundServiceItemPo().getImportTimeStrategy()=="takeoffTime"){
                                        o1Time = o1Flight.getFlightPlanePo().getTakeOffTime();
                                    }
                                    if(o1Flight.getGroundServiceItemPo().getImportTimeStrategy()=="arriveTime"){
                                        o1Time = o1Flight.getFlightPlanePo().getArriveTime();
                                    }
                                }
                                if(o1Flight.getFlightPlanePo().getImportOrExport()=="出港"){
                                    if(o1Flight.getGroundServiceItemPo().getExportTimeStrategy()=="takeoffTime"){
                                        o1Time = o1Flight.getFlightPlanePo().getTakeOffTime();
                                    }
                                    if(o1Flight.getGroundServiceItemPo().getExportTimeStrategy()=="arriveTime"){
                                        o1Time = o1Flight.getFlightPlanePo().getArriveTime();
                                    }
                                }
                                if(o1Flight.getFlightPlanePo().getImportOrExport()=="中转联程"){
                                    if(o1Flight.getGroundServiceItemPo().getTransferProcessStrategy()=="takeoffTime"){
                                        o1Time = o1Flight.getFlightPlanePo().getTakeOffTime();
                                    }
                                    if(o1Flight.getGroundServiceItemPo().getTransferProcessStrategy()=="arriveTime"){
                                        o1Time = o1Flight.getFlightPlanePo().getArriveTime();
                                    }
                                }
                                if(o2Flight.getFlightPlanePo().getImportOrExport()=="进港"){
                                    if(o2Flight.getGroundServiceItemPo().getImportTimeStrategy()=="takeoffTime"){
                                        o2Time = o2Flight.getFlightPlanePo().getTakeOffTime();
                                    }
                                    if(o2Flight.getGroundServiceItemPo().getImportTimeStrategy()=="arriveTime"){
                                        o2Time = o2Flight.getFlightPlanePo().getArriveTime();
                                    }
                                }
                                if(o2Flight.getFlightPlanePo().getImportOrExport()=="出港"){
                                    if(o2Flight.getGroundServiceItemPo().getExportTimeStrategy()=="takeoffTime"){
                                        o2Time = o2Flight.getFlightPlanePo().getTakeOffTime();
                                    }
                                    if(o2Flight.getGroundServiceItemPo().getExportTimeStrategy()=="arriveTime"){
                                        o2Time = o2Flight.getFlightPlanePo().getArriveTime();
                                    }
                                }
                                if(o2Flight.getFlightPlanePo().getImportOrExport()=="中转联程"){
                                    if(o2Flight.getGroundServiceItemPo().getTransferProcessStrategy()=="takeoffTime"){
                                        o2Time = o2Flight.getFlightPlanePo().getTakeOffTime();
                                    }
                                    if(o2Flight.getGroundServiceItemPo().getTransferProcessStrategy()=="arriveTime"){
                                        o2Time = o2Flight.getFlightPlanePo().getArriveTime();
                                    }
                                }
                                if(o1Time!=null&&o2Time!=null){
                                    long o1abs = Math.abs(o1Time.getTime() - baseTime.getTime());
                                    long o2abs = Math.abs(o2Time.getTime() - baseTime.getTime());
                                    if(o1abs!=o2abs){
                                        return  o1abs>o2abs?-1:1;
                                    }
                                }


                            }
                        }
                        if(o1.getServiceTime()==o2.getServiceTime()){
                            return 0;
                        }
                        if(o1.getServiceTime()>o2.getServiceTime()){
                            return 1;
                        }else{
                            return -1;
                        }
                    }
                });
                List<FwUserPo> list= null;
                if(fwUserPos.size()>g.getScheduleBaseNum()){
                    list = fwUserPos.subList(0,g.getScheduleBaseNum());
                }else{
                    list = fwUserPos;
                }

                fwUserDao.save(list);
                gs.setSelectedFwUser(list);
            }
            gs.setGroundServiceItemPo(g);
            gs.setStatus("发布");
            gss.add(gs);
            gs.setGroundServiceSchedulings(groundServiceSchedulings);
        }

        groundServiceSchedulings.setSchedulings(gss);
        groundServiceSchedulingsDao.save(groundServiceSchedulings);
        groundServiceSchedulingDao.save(gss);
        return groundServiceSchedulings;
    }

    @Transactional
    public void scheduleAutos(List<FlightPlanePo> flightPlanePos){

        List<GroundServiceSchedulings>  unfinishedSchedule =entityManager.createQuery("select distinct g from  GroundServiceSchedulings g left join fetch  g.flightPlanePo f left join fetch f.flightInfo left join fetch g.schedulings  s left join fetch s.selectedFwUser left join fetch s.airSecurityVehiclePo  left join fetch s.groundServiceItemPo  where  not(s.status= '结束')").getResultList();


        List<GroundServiceItemPo> groundServiceItemPos = entityManager.createQuery("select distinct g from  GroundServiceItemPo g left join fetch g.airSecurityVehicle left join  fetch  g.teams  t left join fetch t.userList").getResultList();

        for(FlightPlanePo flightPlanePo: flightPlanePos){
            if(flightPlanePo.getTakeOffTime()==null||flightPlanePo.getArriveTime()==null){
                continue;
            }
            Map<String , FlightPlaneSchedule> filterUserMap  = new HashMap<>();
            Map<String ,FlightPlaneSchedule> filterTeamMap = new HashMap<>();
            Map<String ,FlightPlaneSchedule> filterVehicleMap = new HashMap<>();
            GroundServiceSchedulings groundServiceSchedulings = new GroundServiceSchedulings();
            groundServiceSchedulings.setFlightPlanePo (flightPlanePo);
           // groundServiceSchedulings.setPlaneId(flightPlanePo.getPlaneId());
            HashSet<GroundServiceScheduling> gss = new HashSet<GroundServiceScheduling>();
            groundServiceSchedulings.setSchedulings(gss);
            groundServiceSchedulings.setFlightPlanePo(flightPlanePo);
            unfinishedSchedule.add(groundServiceSchedulings);
            for(GroundServiceSchedulings gs :unfinishedSchedule){
                for(GroundServiceScheduling scheduling: gs.getSchedulings()){
                    for(FwUserPo user :scheduling.getSelectedFwUser()){
                        filterUserMap.put(user.getUserId(),new FlightPlaneSchedule(scheduling.getGroundServiceItemPo(),gs.getFlightPlanePo()));
                        filterTeamMap.put(scheduling.getSelectedTeamId(),new FlightPlaneSchedule(scheduling.getGroundServiceItemPo(),gs.getFlightPlanePo()));
                        if(scheduling.getAirSecurityVehiclePo()!=null){
                            filterVehicleMap.put(scheduling.getAirSecurityVehiclePo().getAirSecurityVehicleId(),new FlightPlaneSchedule(scheduling.getGroundServiceItemPo(),gs.getFlightPlanePo()));
                        }

                    }
                }
            }
            for(GroundServiceItemPo  g:groundServiceItemPos){

                List<FwTeamPo> teams = new ArrayList<>(g.getTeams()) ;
                for(int i=0;i<teams.size();i++){
                    if(teams.get(i).getUserList()==null||teams.get(i).getUserList().size()==0){
                        teams.remove(i);
                    }
                }
                if(teams==null||teams.size()==0){
                    continue;
                }
                int userSize= 0;
                for(FwTeamPo teamPo : teams){
                    userSize+=teamPo.getUserList()==null?0:teamPo.getUserList().size();
                }
                if(userSize==0){
                    continue;
                }
                if(!g.getStatus()){
                    continue;
                }
                if(flightPlanePo.getImportOrExport()=="进港"){
                    if(!g.getUseInImport()){
                        continue;
                    }
                }
                if(flightPlanePo.getImportOrExport()=="出港"){
                    if(!g.getUseInExport()){
                        continue;
                    }
                }
                if(flightPlanePo.getImportOrExport()=="中转联程"){
                    if(g.getUseInTransferProcess()){
                        continue;
                    }
                }
                GroundServiceScheduling gs =  new GroundServiceScheduling();
                gs.setGroundServiceItemPo(g);
                List<FwUserPo> fwusers = new ArrayList<FwUserPo>();
                if(g.isHasGroup()){
                    teams.sort(new Comparator<FwTeamPo>() {
                        @Override
                        public int compare(FwTeamPo o1, FwTeamPo o2) {
                            if(filterTeamMap!=null){
                                FlightPlaneSchedule o1Flight= filterTeamMap.get(o1.getTeamId());
                                FlightPlaneSchedule  o2Flight = filterTeamMap.get(o2.getTeamId());;
                                if((o1Flight==null||o2Flight==null)&&!(o1Flight==null&&o2Flight==null)){
                                    return o1Flight==null ?-1:1;
                                }
                                if(o1Flight!=null&&o2Flight!=null){
                                    Date baseTime =  null;
                                    Date o1Time = null;
                                    Date o2Time = null;

                                    if(flightPlanePo.getImportOrExport()=="进港"){
                                        if(g.getImportTimeStrategy()=="takeoffTime"){
                                            baseTime = flightPlanePo.getTakeOffTime();
                                        }
                                        if(g.getImportTimeStrategy()=="arriveTime"){
                                            baseTime = flightPlanePo.getArriveTime();
                                        }
                                    }
                                    if(flightPlanePo.getImportOrExport()=="出港"){
                                        if(g.getExportTimeStrategy()=="takeoffTime"){
                                            baseTime = flightPlanePo.getTakeOffTime();
                                        }
                                        if(g.getExportTimeStrategy()=="arriveTime"){
                                            baseTime = flightPlanePo.getArriveTime();
                                        }
                                    }
                                    if(flightPlanePo.getImportOrExport()=="中转联程"){
                                        if(g.getTransferProcessStrategy()=="takeoffTime"){
                                            baseTime = flightPlanePo.getTakeOffTime();
                                        }
                                        if(g.getTransferProcessStrategy()=="arriveTime"){
                                            baseTime = flightPlanePo.getArriveTime();
                                        }
                                    }

                                    if(o1Flight.getFlightPlanePo().getImportOrExport()=="进港"){
                                        if(o1Flight.getGroundServiceItemPo().getImportTimeStrategy()=="takeoffTime"){
                                            o1Time = o1Flight.getFlightPlanePo().getTakeOffTime();
                                        }
                                        if(o1Flight.getGroundServiceItemPo().getImportTimeStrategy()=="arriveTime"){
                                            o1Time = o1Flight.getFlightPlanePo().getArriveTime();
                                        }
                                    }
                                    if(o1Flight.getFlightPlanePo().getImportOrExport()=="出港"){
                                        if(o1Flight.getGroundServiceItemPo().getExportTimeStrategy()=="takeoffTime"){
                                            o1Time = o1Flight.getFlightPlanePo().getTakeOffTime();
                                        }
                                        if(o1Flight.getGroundServiceItemPo().getExportTimeStrategy()=="arriveTime"){
                                            o1Time = o1Flight.getFlightPlanePo().getArriveTime();
                                        }
                                    }
                                    if(o1Flight.getFlightPlanePo().getImportOrExport()=="中转联程"){
                                        if(o1Flight.getGroundServiceItemPo().getTransferProcessStrategy()=="takeoffTime"){
                                            o1Time = o1Flight.getFlightPlanePo().getTakeOffTime();
                                        }
                                        if(o1Flight.getGroundServiceItemPo().getTransferProcessStrategy()=="arriveTime"){
                                            o1Time = o1Flight.getFlightPlanePo().getArriveTime();
                                        }
                                    }
                                    if(o2Flight.getFlightPlanePo().getImportOrExport()=="进港"){
                                        if(o2Flight.getGroundServiceItemPo().getImportTimeStrategy()=="takeoffTime"){
                                            o2Time = o2Flight.getFlightPlanePo().getTakeOffTime();
                                        }
                                        if(o2Flight.getGroundServiceItemPo().getImportTimeStrategy()=="arriveTime"){
                                            o2Time = o2Flight.getFlightPlanePo().getArriveTime();
                                        }
                                    }
                                    if(o2Flight.getFlightPlanePo().getImportOrExport()=="出港"){
                                        if(o2Flight.getGroundServiceItemPo().getExportTimeStrategy()=="takeoffTime"){
                                            o2Time = o2Flight.getFlightPlanePo().getTakeOffTime();
                                        }
                                        if(o2Flight.getGroundServiceItemPo().getExportTimeStrategy()=="arriveTime"){
                                            o2Time = o2Flight.getFlightPlanePo().getArriveTime();
                                        }
                                    }
                                    if(o2Flight.getFlightPlanePo().getImportOrExport()=="中转联程"){
                                        if(o2Flight.getGroundServiceItemPo().getTransferProcessStrategy()=="takeoffTime"){
                                            o2Time = o2Flight.getFlightPlanePo().getTakeOffTime();
                                        }
                                        if(o2Flight.getGroundServiceItemPo().getTransferProcessStrategy()=="arriveTime"){
                                            o2Time = o2Flight.getFlightPlanePo().getArriveTime();
                                        }
                                    }
                                    if(o1Time!=null&&o2Time!=null){
                                        long o1abs = Math.abs(o1Time.getTime() - baseTime.getTime());
                                        long o2abs = Math.abs(o2Time.getTime() - baseTime.getTime());
                                        if(o1abs!=o2abs){
                                            return  o1abs>o2abs?-1:1;
                                        }
                                    }



                                }
                            }
                            if(o1.getServiceTime()==o2.getServiceTime()){
                                return 0;
                            }
                            if(o1.getServiceTime()>o2.getServiceTime()){
                                return 1;
                            }else{
                                return -1;
                            }
                        }
                    });
                    ArrayList<FwUserPo> ue = new ArrayList<FwUserPo>();
                    ue.addAll(teams.get(0).getUserList());
                    FwTeamPo teamPo = teams.get(0);
                    teamPo.setServiceTime(teamPo.getServiceTime()+1);
                    fwTeamDao.save(teamPo);
                    gs.setSelectedFwUser(ue);
                    gs.setSelectedTeamId(teamPo.getTeamId());

                }else{
                    List<FwUserPo> fwUserPos =  new ArrayList<FwUserPo>();
                    for(FwTeamPo teamPo : teams){
                        if(teamPo.getUserList()!=null&&teamPo.getUserList().size()>0){
                            fwUserPos.addAll(teamPo.getUserList());
                        }
                    }
                    fwUserPos.sort(new Comparator<FwUserPo>() {
                        @Override
                        public int compare(FwUserPo o1, FwUserPo o2) {
                            if(filterTeamMap!=null){
                                FlightPlaneSchedule o1Flight= filterUserMap.get(o1.getUserId());
                                FlightPlaneSchedule  o2Flight = filterUserMap.get(o2.getUserId());;
                                if((o1Flight==null||o2Flight==null)&&!(o1Flight==null&&o2Flight==null)){
                                    return o1Flight==null ?-1:1;
                                }
                                if(o1Flight!=null&&o2Flight!=null){
                                    Date baseTime =  null;
                                    Date o1Time = null;
                                    Date o2Time = null;

                                    if(flightPlanePo.getImportOrExport()=="进港"){
                                        if(g.getImportTimeStrategy()=="takeoffTime"){
                                            baseTime = flightPlanePo.getTakeOffTime();
                                        }
                                        if(g.getImportTimeStrategy()=="arriveTime"){
                                            baseTime = flightPlanePo.getArriveTime();
                                        }
                                    }
                                    if(flightPlanePo.getImportOrExport()=="出港"){
                                        if(g.getExportTimeStrategy()=="takeoffTime"){
                                            baseTime = flightPlanePo.getTakeOffTime();
                                        }
                                        if(g.getExportTimeStrategy()=="arriveTime"){
                                            baseTime = flightPlanePo.getArriveTime();
                                        }
                                    }
                                    if(flightPlanePo.getImportOrExport()=="中转联程"){
                                        if(g.getTransferProcessStrategy()=="takeoffTime"){
                                            baseTime = flightPlanePo.getTakeOffTime();
                                        }
                                        if(g.getTransferProcessStrategy()=="arriveTime"){
                                            baseTime = flightPlanePo.getArriveTime();
                                        }
                                    }

                                    if(o1Flight.getFlightPlanePo().getImportOrExport()=="进港"){
                                        if(o1Flight.getGroundServiceItemPo().getImportTimeStrategy()=="takeoffTime"){
                                            o1Time = o1Flight.getFlightPlanePo().getTakeOffTime();
                                        }
                                        if(o1Flight.getGroundServiceItemPo().getImportTimeStrategy()=="arriveTime"){
                                            o1Time = o1Flight.getFlightPlanePo().getArriveTime();
                                        }
                                    }
                                    if(o1Flight.getFlightPlanePo().getImportOrExport()=="出港"){
                                        if(o1Flight.getGroundServiceItemPo().getExportTimeStrategy()=="takeoffTime"){
                                            o1Time = o1Flight.getFlightPlanePo().getTakeOffTime();
                                        }
                                        if(o1Flight.getGroundServiceItemPo().getExportTimeStrategy()=="arriveTime"){
                                            o1Time = o1Flight.getFlightPlanePo().getArriveTime();
                                        }
                                    }
                                    if(o1Flight.getFlightPlanePo().getImportOrExport()=="中转联程"){
                                        if(o1Flight.getGroundServiceItemPo().getTransferProcessStrategy()=="takeoffTime"){
                                            o1Time = o1Flight.getFlightPlanePo().getTakeOffTime();
                                        }
                                        if(o1Flight.getGroundServiceItemPo().getTransferProcessStrategy()=="arriveTime"){
                                            o1Time = o1Flight.getFlightPlanePo().getArriveTime();
                                        }
                                    }
                                    if(o2Flight.getFlightPlanePo().getImportOrExport()=="进港"){
                                        if(o2Flight.getGroundServiceItemPo().getImportTimeStrategy()=="takeoffTime"){
                                            o2Time = o2Flight.getFlightPlanePo().getTakeOffTime();
                                        }
                                        if(o2Flight.getGroundServiceItemPo().getImportTimeStrategy()=="arriveTime"){
                                            o2Time = o2Flight.getFlightPlanePo().getArriveTime();
                                        }
                                    }
                                    if(o2Flight.getFlightPlanePo().getImportOrExport()=="出港"){
                                        if(o2Flight.getGroundServiceItemPo().getExportTimeStrategy()=="takeoffTime"){
                                            o2Time = o2Flight.getFlightPlanePo().getTakeOffTime();
                                        }
                                        if(o2Flight.getGroundServiceItemPo().getExportTimeStrategy()=="arriveTime"){
                                            o2Time = o2Flight.getFlightPlanePo().getArriveTime();
                                        }
                                    }
                                    if(o2Flight.getFlightPlanePo().getImportOrExport()=="中转联程"){
                                        if(o2Flight.getGroundServiceItemPo().getTransferProcessStrategy()=="takeoffTime"){
                                            o2Time = o2Flight.getFlightPlanePo().getTakeOffTime();
                                        }
                                        if(o2Flight.getGroundServiceItemPo().getTransferProcessStrategy()=="arriveTime"){
                                            o2Time = o2Flight.getFlightPlanePo().getArriveTime();
                                        }
                                    }
                                    if(o1Time!=null&&o2Time!=null){
                                        long o1abs = Math.abs(o1Time.getTime() - baseTime.getTime());
                                        long o2abs = Math.abs(o2Time.getTime() - baseTime.getTime());
                                        if(o1abs!=o2abs){
                                            return  o1abs>o2abs?-1:1;
                                        }
                                    }                                }
                            }
                            if(o1.getServiceTime()==o2.getServiceTime()){
                                return 0;
                            }
                            if(o1.getServiceTime()>o2.getServiceTime()){
                                return 1;
                            }else{
                                return -1;
                            }
                        }
                    });
                    List<FwUserPo> list= null;
                    if(fwUserPos.size()>g.getScheduleBaseNum()){
                        list = fwUserPos.subList(0,g.getScheduleBaseNum());
                    }else{
                        list = fwUserPos;
                    }

                    fwUserDao.save(list);
                    gs.setSelectedFwUser(list);
                }
                if(g.getAirSecurityVehicle()!=null&&g.getAirSecurityVehicle().size()!=0){
                   List <AirSecurityVehiclePo> list = new ArrayList<>(g.getAirSecurityVehicle());
                   list.sort(new Comparator<AirSecurityVehiclePo>() {
                       @Override
                       public int compare(AirSecurityVehiclePo o1, AirSecurityVehiclePo o2) {
                           if(filterVehicleMap!=null){
                               FlightPlaneSchedule o1Flight= filterVehicleMap.get(o1.getAirSecurityVehicleId());
                               FlightPlaneSchedule  o2Flight = filterVehicleMap.get(o2.getAirSecurityVehicleId());;
                               if((o1Flight==null||o2Flight==null)&&!(o1Flight==null&&o2Flight==null)){
                                   return o1Flight==null ?-1:1;
                               }
                               if(o1Flight!=null&&o2Flight!=null){
                                   Date baseTime =  null;
                                   Date o1Time = null;
                                   Date o2Time = null;

                                   if(flightPlanePo.getImportOrExport()=="进港"){
                                       if(g.getImportTimeStrategy()=="takeoffTime"){
                                           baseTime = flightPlanePo.getTakeOffTime();
                                       }
                                       if(g.getImportTimeStrategy()=="arriveTime"){
                                           baseTime = flightPlanePo.getArriveTime();
                                       }
                                   }
                                   if(flightPlanePo.getImportOrExport()=="出港"){
                                       if(g.getExportTimeStrategy()=="takeoffTime"){
                                           baseTime = flightPlanePo.getTakeOffTime();
                                       }
                                       if(g.getExportTimeStrategy()=="arriveTime"){
                                           baseTime = flightPlanePo.getArriveTime();
                                       }
                                   }
                                   if(flightPlanePo.getImportOrExport()=="中转联程"){
                                       if(g.getTransferProcessStrategy()=="takeoffTime"){
                                           baseTime = flightPlanePo.getTakeOffTime();
                                       }
                                       if(g.getTransferProcessStrategy()=="arriveTime"){
                                           baseTime = flightPlanePo.getArriveTime();
                                       }
                                   }

                                   if(o1Flight.getFlightPlanePo().getImportOrExport()=="进港"){
                                       if(o1Flight.getGroundServiceItemPo().getImportTimeStrategy()=="takeoffTime"){
                                           o1Time = o1Flight.getFlightPlanePo().getTakeOffTime();
                                       }
                                       if(o1Flight.getGroundServiceItemPo().getImportTimeStrategy()=="arriveTime"){
                                           o1Time = o1Flight.getFlightPlanePo().getArriveTime();
                                       }
                                   }
                                   if(o1Flight.getFlightPlanePo().getImportOrExport()=="出港"){
                                       if(o1Flight.getGroundServiceItemPo().getExportTimeStrategy()=="takeoffTime"){
                                           o1Time = o1Flight.getFlightPlanePo().getTakeOffTime();
                                       }
                                       if(o1Flight.getGroundServiceItemPo().getExportTimeStrategy()=="arriveTime"){
                                           o1Time = o1Flight.getFlightPlanePo().getArriveTime();
                                       }
                                   }
                                   if(o1Flight.getFlightPlanePo().getImportOrExport()=="中转联程"){
                                       if(o1Flight.getGroundServiceItemPo().getTransferProcessStrategy()=="takeoffTime"){
                                           o1Time = o1Flight.getFlightPlanePo().getTakeOffTime();
                                       }
                                       if(o1Flight.getGroundServiceItemPo().getTransferProcessStrategy()=="arriveTime"){
                                           o1Time = o1Flight.getFlightPlanePo().getArriveTime();
                                       }
                                   }
                                   if(o2Flight.getFlightPlanePo().getImportOrExport()=="进港"){
                                       if(o2Flight.getGroundServiceItemPo().getImportTimeStrategy()=="takeoffTime"){
                                           o2Time = o2Flight.getFlightPlanePo().getTakeOffTime();
                                       }
                                       if(o2Flight.getGroundServiceItemPo().getImportTimeStrategy()=="arriveTime"){
                                           o2Time = o2Flight.getFlightPlanePo().getArriveTime();
                                       }
                                   }
                                   if(o2Flight.getFlightPlanePo().getImportOrExport()=="出港"){
                                       if(o2Flight.getGroundServiceItemPo().getExportTimeStrategy()=="takeoffTime"){
                                           o2Time = o2Flight.getFlightPlanePo().getTakeOffTime();
                                       }
                                       if(o2Flight.getGroundServiceItemPo().getExportTimeStrategy()=="arriveTime"){
                                           o2Time = o2Flight.getFlightPlanePo().getArriveTime();
                                       }
                                   }
                                   if(o2Flight.getFlightPlanePo().getImportOrExport()=="中转联程"){
                                       if(o2Flight.getGroundServiceItemPo().getTransferProcessStrategy()=="takeoffTime"){
                                           o2Time = o2Flight.getFlightPlanePo().getTakeOffTime();
                                       }
                                       if(o2Flight.getGroundServiceItemPo().getTransferProcessStrategy()=="arriveTime"){
                                           o2Time = o2Flight.getFlightPlanePo().getArriveTime();
                                       }
                                   }
                                   if(o1Time!=null&&o2Time!=null){
                                       long o1abs = Math.abs(o1Time.getTime() - baseTime.getTime());
                                       long o2abs = Math.abs(o2Time.getTime() - baseTime.getTime());
                                       if(o1abs!=o2abs){
                                           return  o1abs>o2abs?-1:1;
                                       }
                                   }
                               }
                           }
                           return 0;
                       }
                   });
                   gs.setAirSecurityVehiclePo(list.get(0));
                }

                gs.setGroundServiceItemPo(g);
                gs.setStatus("发布");
                gss.add(gs);
                gs.setGroundServiceSchedulings(groundServiceSchedulings);
            }

            groundServiceSchedulings.setSchedulings(gss);
            groundServiceSchedulingsDao.save(groundServiceSchedulings);
            groundServiceSchedulingDao.save(gss);
            }

    }

    public void scheduleAll(){
        List<FlightPlanePo > list =  entityManager.createQuery("select f from   GroundServiceSchedulings g right join   g.flightPlanePo f left join fetch f.flightInfo  where g is null").getResultList();
        try {
            scheduleAutos(list);
        }catch (Exception e){
            e.printStackTrace();
        }

     }




    public List mySchedule(Date startDate, Date endDate,  FwUserPo user){
        String sql ="SELECT     distinct   g FROM   GroundServiceScheduling g join fetch g.groundServiceSchedulings  gs  join fetch gs.flightPlanePo f left join fetch f.courseNodePos   join fetch f.flightInfo    " +
                "     join  fetch g.selectedFwUser u   join fetch g.airSecurityVehiclePo " +
                "        where u.userId = :userId      " +
                "       and ( " +
                "               (f.importOrExport='进港' and (UNIX_TIMESTAMP(f.arriveTime)+g.groundServiceItemPo.difference*60) between :startDate and :endDate ) " +
                "  " +
                "            or (f.importOrExport='出港' and ( UNIX_TIMESTAMP(f.takeOffTime)-g.groundServiceItemPo.difference*60) between :startDate and :endDate)  " +
                "                         " +
                "            or (f.importOrExport='中转联程' and g.groundServiceItemPo.transferProcessStrategy='takeOffTime' and (UNIX_TIMESTAMP(f.takeOffTime)-g.groundServiceItemPo.difference*60)  between :startDate and :endDate)  " +
                "                          " +
                "            or (f.importOrExport='中转联程' and g.groundServiceItemPo.transferProcessStrategy='arriveTime' and ( UNIX_TIMESTAMP(f.arriveTime)+g.groundServiceItemPo.difference*60) between :startDate and :endDate)  " +
                "                           " +
                "       ) " ;
        Query query= entityManager.createQuery(sql);
        if(startDate==null){
            Calendar calendar =  Calendar.getInstance();
            calendar.add(Calendar.DAY_OF_YEAR,-60);
            startDate = calendar.getTime();
        }
        if(endDate==null){
            Calendar calendar =  Calendar.getInstance();
            calendar.add(Calendar.DAY_OF_YEAR,90);
            endDate = calendar.getTime();
        }
        query.setParameter("startDate", (Long)(startDate.getTime()/1000));
        query.setParameter("endDate", (Long)(endDate.getTime()/1000));
        query.setParameter("userId",user.getUserId());
        List list =query.getResultList();
        return list;
    }
    public List<GroundServiceFlightPlaneView>  queryScheduleToday(int beforeHour,int afterHour){

        String quString = "select f,gs from GroundServiceSchedulings gs join gs.schedulings g ,  FlightPlanePo f  where gs.planeId = f.planeId and" +
                " ((f.takeOffTime between :startDate and :endDate  and f.importOrExport='出港') or (f.arriveTime between :startDate and :endDate  and f.importOrExport='进港')or ( (f.arriveTime between :startDate and :endDate or f.arriveTime between :startDate and :endDate)  and f.importOrExport='中转联程')) group by f ,gs";
        Query query = entityManager.createQuery(quString);
        Calendar calendar = Calendar.getInstance();
        calendar.add(Calendar.HOUR,0-beforeHour);
        Date startDate =  calendar.getTime();
        calendar.setTime(new Date());
        calendar.add(Calendar.HOUR,afterHour);
        Date endDate = calendar.getTime();
        query.setParameter("startDate",startDate,TemporalType.TIMESTAMP);
        query.setParameter("endDate",endDate,TemporalType.TIMESTAMP);
        return query.getResultList();
    }

    public List<GroundServiceSchedulings> queryScheduled( Date startDate,Date endDate,String flightInfoId){
        String quString="";
        quString = "select distinct gs from  GroundServiceSchedulings gs left join fetch  gs.flightPlanePo f left join fetch f.flightInfo left join fetch gs.schedulings  g left join fetch g.selectedFwUser left join fetch g.airSecurityVehiclePo  left join fetch g.groundServiceItemPo    where 1=1 ";
        if(StringUtils.isNoneBlank(flightInfoId)){
            quString += "  and f.flightInfo.flightInfoId= :flightInfoId";

        }
        quString+= " and (f.estimatedTime between :startDate and :endDate  or f.expectDate  between :startDate and :endDate)";
//         quString += "  and ((g.groundServiceItemPo.timeStrategy='起飞时间'and g.groundServiceItemPo.beforeOrAfter='基准时间前' and ( UNIX_TIMESTAMP(f.takeOffTime)-g.groundServiceItemPo.difference*60) between :startDate and :endDate )" +
//                    "        or (g.groundServiceItemPo.timeStrategy='起飞时间'and g.groundServiceItemPo.beforeOrAfter='基准时间后' and ( UNIX_TIMESTAMP(f.takeOffTime)+g.groundServiceItemPo.difference*60) between :startDate and :endDate)" +
//                    "        or (g.groundServiceItemPo.timeStrategy='落地时间'and g.groundServiceItemPo.beforeOrAfter='基准时间前' and ( UNIX_TIMESTAMP(f.arriveTime)-g.groundServiceItemPo.difference*60)  between :startDate and :endDate)" +
//                    "        or (g.groundServiceItemPo.timeStrategy='落地时间'and g.groundServiceItemPo.beforeOrAfter='基准时间后' and ( UNIX_TIMESTAMP(f.arriveTime)+g.groundServiceItemPo.difference*60) between :startDate and :endDate) )";
        Query query= entityManager.createQuery(quString);
        if(StringUtils.isNoneBlank(flightInfoId)){
            query.setParameter("flightInfoId",flightInfoId);
        }
        query.setParameter("startDate", startDate,TemporalType.DATE);
        query.setParameter("endDate", endDate,TemporalType.DATE);
        return query.getResultList();
    }

    @Transactional
    public GroundServiceSchedulings save(GroundServiceSchedulings gs){
        Set<GroundServiceScheduling> set=gs.getSchedulings();
        GroundServiceSchedulings gss = groundServiceSchedulingsDao.findOne(gs.getId());
        List<GroundServiceScheduling> list =  new ArrayList(gss.getSchedulings());
        HashMap<String ,GroundServiceScheduling> map =  new HashMap();
        for(GroundServiceScheduling g : set){
            g.setGroundServiceSchedulings(gs);
            g= groundServiceSchedulingDao.save(g);
            map.put(g.getGssId(),g);
        }
        for(int i =0;i<list.size();i++){
            GroundServiceScheduling gsg = list.get(i);
            if(map.get(gsg.getGssId())==null){
                groundServiceSchedulingDao.delete(gsg.getGssId());
            }
        }
       return gs;
    }
}
